import { useState, useEffect } from "react";
import styles from "./QueryPendingFreight.module.css";

interface PendingFreight {
    Id: number;
    TeamId: string;
    TeamName: string;
    WarehouseName: string;
    TrackingNumber: string;
    ShippingNumber: string;
    Weight: number;
    Long: number;
    Wide: number;
    High: number;
    Addressee: string;
}

// API响应数据的接口定义
interface ApiResponseItem {
    id?: number;
    Id?: number;
    teamId?: string;
    TeamId?: string;
    teamName?: string;
    TeamName?: string;
    team?: string;
    warehouseName?: string;
    WarehouseName?: string;
    warehousename?: string;
    trackingNumber?: string;
    TrackingNumber?: string;
    trackingnumber?: string;
    shippingNumber?: string;
    ShippingNumber?: string;
    shippingnumber?: string;
    weight?: number | string;
    Weight?: number | string;
    long?: number | string;
    Long?: number | string;
    wide?: number | string;
    Wide?: number | string;
    high?: number | string;
    High?: number | string;
    addressee?: string;
    Addressee?: string;
}

interface QueryParams {
    trackingNumber: string;
    shippingNumber: string;
    warehouseName: string;
    teamName: string;
}

const BASE_URL = 'http://localhost:5233';

const QueryPendingFreight = () => {
    const [PendingList, setPendingList] = useState<PendingFreight[]>([]);
    const [error, setError] = useState<string | null>(null);
    const [loading, setLoading] = useState(true);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [editingFreight, setEditingFreight] = useState<PendingFreight | null>(null);
    const [isConfirmModalOpen, setIsConfirmModalOpen] = useState(false);
    const [deleteId, setDeleteId] = useState<number | null>(null);
    const [queryParams, setQueryParams] = useState<QueryParams>({
        trackingNumber: '',
        shippingNumber: '',
        warehouseName: '',
        teamName: ''
    });
    const [warehouses, setWarehouses] = useState<string[]>([]);
    const [teams, setTeams] = useState<string[]>([]);

    // 获取仓库和团队列表
    useEffect(() => {
        const fetchOptions = async () => {
            try {
                // 这里应该调用实际的API来获取仓库和团队列表
                // 暂时使用模拟数据
                setWarehouses(['千葉裕宝富里倉庫', '東京日暮里倉庫', '商城对接仓']);
                setTeams(['易帆转运', '深圳万品元', '深圳畅运达12','畅运达商城']);
            } catch (error) {
                console.error('获取选项数据失败:', error);
            }
        };

        fetchOptions();
    }, []);

    // 从数据库获取数据
    const fetchData = async (params: QueryParams) => {
        try {
            setLoading(true);
            console.log('开始获取数据...查询参数:', params);
            
            // 构建查询参数
            const queryString = new URLSearchParams({
                ...(params.trackingNumber && { trackingNumber: params.trackingNumber }),
                ...(params.shippingNumber && { shippingNumber: params.shippingNumber }),
                ...(params.warehouseName && { warehouseName: params.warehouseName }),
                ...(params.teamName && { teamName: params.teamName })
            }).toString();

            const url = `${BASE_URL}/api/PendingFreight/QueryPendingFreight${queryString ? `?${queryString}` : ''}`;
            
            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json'
                }
            });

            console.log('服务器响应状态:', response.status);
            const responseText = await response.text();
            console.log('原始响应数据:', responseText);

            if (!response.ok) {
                throw new Error(`服务器响应错误: ${response.status}`);
            }

            // 尝试解析JSON
            const result = JSON.parse(responseText);
            console.log('解析后的数据:', result);

            if (result && result.code === 200 && Array.isArray(result.data)) {
                console.log('设置data字段数据:', result.data);
                console.log('数据第一项详细信息:', result.data[0]);
                
                // 添加数据验证和转换
                const processedData = result.data.map((item: ApiResponseItem, index: number) => {
                    console.log(`处理第${index}项数据:`, item);
                    return {
                        Id: item.id || item.Id || index + 1,
                        TeamId: item.teamId || item.TeamId || '',
                        TeamName: item.teamName || item.TeamName || item.team || '未知团队',
                        WarehouseName: item.warehouseName || item.WarehouseName || item.warehousename || '未知仓库',
                        TrackingNumber: item.trackingNumber || item.TrackingNumber || item.trackingnumber || '',
                        ShippingNumber: item.shippingNumber || item.ShippingNumber || item.shippingnumber || '',
                        Weight: Number(item.weight || item.Weight || 0),
                        Long: Number(item.long || item.Long || 0),
                        Wide: Number(item.wide || item.Wide || 0),
                        High: Number(item.high || item.High || 0),
                        Addressee: item.addressee || item.Addressee || '未知收件人'
                    };
                });
                
                console.log('处理后的数据:', processedData);
                setPendingList(processedData);
            } else {
                console.warn('API返回的数据结构不符合预期:', result);
                setPendingList([]);
            }
            setError(null);
        } catch (error) {
            console.error('获取数据失败:', error);
            let errorMessage = '获取数据失败';
            
            if (error instanceof Error) {
                if (error.message.includes('Failed to fetch') || error.message.includes('ERR_CONNECTION_REFUSED')) {
                    errorMessage = '无法连接到服务器，请确保后端服务已启动在端口5233';
                } else {
                    errorMessage = error.message;
                }
            }
            
            setError(errorMessage);
            setPendingList([]);
        } finally {
            setLoading(false);
        }
    };

    // 初始加载数据
    useEffect(() => {
        fetchData(queryParams);
    }, []);

    // 处理查询参数变化
    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
        const { name, value } = e.target;
        setQueryParams(prev => ({
            ...prev,
            [name]: value
        }));
    };

    // 处理查询按钮点击
    const handleSearch = () => {
        fetchData(queryParams);
    };

    // 处理重置按钮点击
    const handleReset = () => {
        setQueryParams({
            trackingNumber: '',
            shippingNumber: '',
            warehouseName: '',
            teamName: ''
        });
        fetchData({
            trackingNumber: '',
            shippingNumber: '',
            warehouseName: '',
            teamName: ''
        });
    };

    // 获取单条数据
    const fetchFreightById = async (id: number) => {
        try {
            const response = await fetch(`${BASE_URL}/api/PendingFreight/FTPendingFreight?Id=${id}`, {
                method: 'POST',
                headers: {
                    'Accept': 'text/plain'
                }
            });

            if (!response.ok) {
                throw new Error(`获取数据失败: ${response.status}`);
            }

            const data = await response.json();
            
            if (data && data.code === 200 && data.data) {
                // 检查data.data是否是数组，如果是数组取第一个元素
                const item = Array.isArray(data.data) ? data.data[0] : data.data;
                
                if (item) {
                    setEditingFreight({
                        Id: item.id || item.Id || id,
                        TeamId: item.teamId || item.TeamId || '',
                        TeamName: item.teamName || item.TeamName || item.team || '',
                        WarehouseName: item.warehouseName || item.WarehouseName || item.warehousename || '',
                        TrackingNumber: item.trackingNumber || item.TrackingNumber || item.trackingnumber || '',
                        ShippingNumber: item.shippingNumber || item.ShippingNumber || item.shippingnumber || '',
                        Weight: Number(item.weight || item.Weight || 0),
                        Long: Number(item.long || item.Long || 0),
                        Wide: Number(item.wide || item.Wide || 0),
                        High: Number(item.high || item.High || 0),
                        Addressee: item.addressee || item.Addressee || ''
                    });
                    setIsEditModalOpen(true);
                } else {
                    // 如果API没有返回有效数据，使用表格中的数据
                    const listItem = PendingList.find(item => item.Id === id);
                    if (listItem) {
                        setEditingFreight({ ...listItem });
                        setIsEditModalOpen(true);
                    } else {
                        setError('无法找到对应的数据');
                    }
                }
            } else {
                // 如果API调用失败，使用表格中的数据
                const listItem = PendingList.find(item => item.Id === id);
                if (listItem) {
                    setEditingFreight({ ...listItem });
                    setIsEditModalOpen(true);
                } else {
                    setError('无法获取数据详情');
                }
            }
        } catch (error) {
            console.error('获取单条数据失败:', error);
            // 如果API调用失败，使用表格中的数据
            const listItem = PendingList.find(item => item.Id === id);
            if (listItem) {
                setEditingFreight({ ...listItem });
                setIsEditModalOpen(true);
            } else {
                setError(error instanceof Error ? error.message : '获取数据失败');
            }
        }
    };

    // 更新数据
    const handleUpdate = async () => {
        if (!editingFreight) return;

        try {
            const response = await fetch(`${BASE_URL}/api/PendingFreight/UpdatePendingFreight`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    id: editingFreight.Id,
                    team: editingFreight.TeamName,
                    warehouseName: editingFreight.WarehouseName,
                    trackingNumber: editingFreight.TrackingNumber,
                    shippingNumber: editingFreight.ShippingNumber,
                    weight: editingFreight.Weight,
                    long: editingFreight.Long,
                    wide: editingFreight.Wide,
                    high: editingFreight.High,
                    addressee: editingFreight.Addressee
                })
            });

            if (!response.ok) {
                throw new Error(`更新失败: ${response.status}`);
            }

            const result = await response.json();
            if (result.code === 200) {
                setIsEditModalOpen(false);
                fetchData(queryParams); // 刷新列表
            } else {
                throw new Error(result.message || '更新失败');
            }
        } catch (error) {
            console.error('更新数据失败:', error);
            setError(error instanceof Error ? error.message : '更新失败');
        }
    };

    // 处理编辑按钮点击
    const handleEdit = (item: PendingFreight) => {
        fetchFreightById(item.Id);
    };

    // 处理输入变化
    const handleEditInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        if (!editingFreight) return;

        setEditingFreight(prev => {
            if (!prev) return prev;
            return {
                ...prev,
                [name]: name === 'Weight' || name === 'Long' || name === 'Wide' || name === 'High'
                    ? Number(value)
                    : value
            };
        });
    };

    // 删除数据
    const handleDelete = async (id: number) => {
        setDeleteId(id);
        setIsConfirmModalOpen(true);
    };

    // 确认删除
    const confirmDelete = async () => {
        if (!deleteId) return;

        try {
            const response = await fetch(`${BASE_URL}/api/PendingFreight/DeletePendingFreight?Id=${deleteId}`, {
                method: 'DELETE',
                headers: {
                    'Accept': 'text/plain'
                }
            });

            if (!response.ok) {
                throw new Error(`删除失败: ${response.status}`);
            }

            const result = await response.json();
            if (result.code === 200) {
                // 删除成功，刷新列表
                fetchData(queryParams);
                alert('删除成功');
            } else {
                throw new Error(result.message || '删除失败');
            }
        } catch (error) {
            console.error('删除数据失败:', error);
            alert(error instanceof Error ? error.message : '删除失败');
        } finally {
            setIsConfirmModalOpen(false);
            setDeleteId(null);
        }
    };

    // 取消删除
    const cancelDelete = () => {
        setIsConfirmModalOpen(false);
        setDeleteId(null);
    };

    if (loading) {
        return <div className={styles.loading}>加载中...</div>;
    }

    return (
        <div className={styles.container}>
            <h1 className={styles.title}>待发货运订单</h1>
            
            {/* 查询表单 */}
            <div className={styles.queryForm}>
                <div className={styles.formRow}>
                    <div className={styles.formItem}>
                        <input
                            type="text"
                            name="trackingNumber"
                            value={queryParams.trackingNumber}
                            onChange={handleInputChange}
                            placeholder="发货单号/转运单号"
                            className={styles.input}
                        />
                    </div>
                    <div className={styles.formItem}>
                        <input
                            type="text"
                            name="shippingNumber"
                            value={queryParams.shippingNumber}
                            onChange={handleInputChange}
                            placeholder="出库单号"
                            className={styles.input}
                        />
                    </div>
                    <div className={styles.formItem}>
                        <select
                            name="warehouseName"
                            value={queryParams.warehouseName}
                            onChange={handleInputChange}
                            className={styles.select}
                        >
                            <option value="">= 仓库 =</option>
                            {warehouses.map(warehouse => (
                                <option key={warehouse} value={warehouse}>
                                    {warehouse}
                                </option>
                            ))}
                        </select>
                    </div>
                    <div className={styles.formItem}>
                        <select
                            name="teamName"
                            value={queryParams.teamName}
                            onChange={handleInputChange}
                            className={styles.select}
                        >
                            <option value="">= 团队 =</option>
                            {teams.map(team => (
                                <option key={team} value={team}>
                                    {team}
                                </option>
                            ))}
                        </select>
                    </div>
                    <div className={styles.formItem}>
                        <button onClick={handleSearch} className={styles.searchButton}>
                            🔍 搜索
                        </button>
                        <button onClick={handleReset} className={styles.resetButton}>
                            ↺ 重置
                        </button>
                    </div>
                </div>
            </div>

            {error ? (
                <div className={styles.error} style={{ color: 'red', padding: '20px' }}>
                    <p>错误: {error}</p>
                    <p>请确保:</p>
                    <ul>
                        <li>后端服务已启动</li>
                        <li>服务运行在正确的端口 (5233)</li>
                        <li>API路径正确</li>
                    </ul>
                </div>
            ) : PendingList.length === 0 ? (
                <div className={styles.empty}>
                    <p>暂无数据</p>
                </div>
            ) : (
                <>
                    <div style={{ marginBottom: '20px' }}>
                        <p>当前数据条数: {PendingList.length}</p>
                        <details style={{ marginTop: '10px' }}>
                            <summary>调试信息（点击展开）</summary>
                            <pre style={{ backgroundColor: '#f5f5f5', padding: '10px', fontSize: '12px', overflow: 'auto' }}>
                                {JSON.stringify(PendingList, null, 2)}
                            </pre>
                        </details>
                    </div>
                    <table className={styles.table}>
                        <thead>
                            <tr>
                                <th>序号</th>
                                <th>团队</th>
                                <th>仓库名称</th>
                                <th>运单号</th>
                                <th>出库单号</th>
                                <th>重量(KG)</th>
                                <th>长(CM)</th>
                                <th>宽(CM)</th>
                                <th>高(CM)</th>
                                <th>收件人</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {PendingList.map((item, index) => (
                                <tr key={`${item.Id}-${index}`} style={{border: '1px solid #ddd'}}>
                                    <td>{item.Id || '无'}</td>
                                    <td>{item.TeamName || '无'}</td>
                                    <td>{item.WarehouseName || '无'}</td>
                                    <td>{item.TrackingNumber || '无'}</td>
                                    <td>{item.ShippingNumber || '无'}</td>
                                    <td>{item.Weight || 0}</td>
                                    <td>{item.Long || 0}</td>
                                    <td>{item.Wide || 0}</td>
                                    <td>{item.High || 0}</td>
                                    <td>{item.Addressee || '无'}</td>
                                    <td className={styles.operationCell}>
                                        <button 
                                            className={`${styles.operationButton} ${styles.editButton}`}
                                            onClick={() => handleEdit(item)}
                                        >
                                            编辑
                                        </button>
                                        <button className={`${styles.operationButton} ${styles.deleteButton}`} onClick={() => handleDelete(item.Id)}>
                                            删除
                                        </button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </>
            )}

            {/* 编辑模态框 */}
            {isEditModalOpen && editingFreight && (
                <div className={styles.modal}>
                    <div className={styles.modalContent}>
                        <div className={styles.modalHeader}>
                            <h2 className={styles.modalTitle}>编辑运单信息</h2>
                            <button 
                                className={styles.closeButton}
                                onClick={() => setIsEditModalOpen(false)}
                            >
                                ×
                            </button>
                        </div>
                        
                        <div className={styles.modalForm}>
                            <div className={styles.modalFormItem}>
                                <label>团队</label>
                                <select
                                    name="TeamName"
                                    value={editingFreight.TeamName || ''}
                                    onChange={e => setEditingFreight({...editingFreight, TeamName: e.target.value})}
                                >
                                    <option value="">请选择团队</option>
                                    {teams.map(team => (
                                        <option key={team} value={team}>{team}</option>
                                    ))}
                                </select>
                            </div>
                            <div className={styles.modalFormItem}>
                                <label>仓库名称</label>
                                <select
                                    name="WarehouseName"
                                    value={editingFreight.WarehouseName || ''}
                                    onChange={e => setEditingFreight({...editingFreight, WarehouseName: e.target.value})}
                                >
                                    <option value="">请选择仓库</option>
                                    {warehouses.map(warehouse => (
                                        <option key={warehouse} value={warehouse}>{warehouse}</option>
                                    ))}
                                </select>
                            </div>
                            <div className={styles.modalFormItem}>
                                <label>运单号</label>
                                <input
                                    type="text"
                                    name="TrackingNumber"
                                    value={editingFreight.TrackingNumber || ''}
                                    onChange={handleEditInputChange}
                                />
                            </div>
                            <div className={styles.modalFormItem}>
                                <label>出库单号</label>
                                <input
                                    type="text"
                                    name="ShippingNumber"
                                    value={editingFreight.ShippingNumber || ''}
                                    onChange={handleEditInputChange}
                                />
                            </div>
                            <div className={styles.modalFormItem}>
                                <label>重量(KG)</label>
                                <input
                                    type="number"
                                    name="Weight"
                                    value={editingFreight.Weight || ''}
                                    onChange={handleEditInputChange}
                                />
                            </div>
                            <div className={styles.modalFormItem}>
                                <label>长(CM)</label>
                                <input
                                    type="number"
                                    name="Long"
                                    value={editingFreight.Long || ''}
                                    onChange={handleEditInputChange}
                                />
                            </div>
                            <div className={styles.modalFormItem}>
                                <label>宽(CM)</label>
                                <input
                                    type="number"
                                    name="Wide"
                                    value={editingFreight.Wide || ''}
                                    onChange={handleEditInputChange}
                                />
                            </div>
                            <div className={styles.modalFormItem}>
                                <label>高(CM)</label>
                                <input
                                    type="number"
                                    name="High"
                                    value={editingFreight.High || ''}
                                    onChange={handleEditInputChange}
                                />
                            </div>
                            <div className={styles.modalFormItem}>
                                <label>收件人</label>
                                <input
                                    type="text"
                                    name="Addressee"
                                    value={editingFreight.Addressee || ''}
                                    onChange={handleEditInputChange}
                                />
                            </div>
                        </div>
                        <div className={styles.modalButtons}>
                            <button 
                                className={styles.cancelButton}
                                onClick={() => setIsEditModalOpen(false)}
                            >
                                取消
                            </button>
                            <button 
                                className={styles.saveButton}
                                onClick={handleUpdate}
                            >
                                保存
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* 确认删除模态框 */}
            {isConfirmModalOpen && deleteId && (
                <div className={styles.modal}>
                    <div className={styles.modalContent}>
                        <div className={styles.modalHeader}>
                            <h2 className={styles.modalTitle}>确认删除</h2>
                            <button 
                                className={styles.closeButton}
                                onClick={cancelDelete}
                            >
                                ×
                            </button>
                        </div>
                        
                        <div className={styles.modalMessage}>
                            <p>确定要删除这条记录吗？此操作不可恢复。</p>
                        </div>
                        <div className={styles.modalButtons}>
                            <button 
                                className={styles.cancelButton}
                                onClick={cancelDelete}
                            >
                                取消
                            </button>
                            <button 
                                className={styles.confirmButton}
                                onClick={confirmDelete}
                            >
                                确认
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default QueryPendingFreight;